import 'dart:io';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:dio/dio.dart';
import 'package:flutterupdatedemo/update_entity.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:path_provider/path_provider.dart';
import 'package:url_launcher/url_launcher.dart';
import 'package:install_plugin/install_plugin.dart';
import 'package:package_info/package_info.dart';

enum DownloadStatus { easy, busy, finish, error }

class UpdateDialog extends StatefulWidget {
  final UpdateEntity entity;

  UpdateDialog(this.entity);

  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return UpdateDialogState();
  }
}

class UpdateDialogState extends State<UpdateDialog> {
  Dio dio;
  DownloadStatus _downloadStatus = DownloadStatus.easy;
  String _currentProgressPresent = "0%";
  double _currentProgress = 0.0;
  File _file;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    dio = new Dio();
  }

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Container(
      height: 300.0,
      decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.all(Radius.circular(5.0))),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.stretch,
        children: <Widget>[
          ClipRRect(
            borderRadius: BorderRadius.only(
                topLeft: Radius.circular(5.0), topRight: Radius.circular(5.0)),
            child: Image.asset('assets/header.png'),
          ),
          Padding(
            padding: EdgeInsets.all(10.0),
            child: Text(
              '新版本更新',
              style: TextStyle(color: Colors.black),
            ),
          ),
          Expanded(
            child: Padding(
              padding: EdgeInsets.symmetric(horizontal: 10.0),
              child: Text(
                widget.entity.updateContent,
                style: TextStyle(color: Colors.black),
              ),
            ),
          ),
          getBottomWidget()
        ],
      ),
    );
  }

  getBottomWidget() {
    switch (_downloadStatus) {
      case DownloadStatus.easy:
        return Row(
          crossAxisAlignment: CrossAxisAlignment.center,
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            CupertinoButton(
              padding: EdgeInsets.zero,
              child: Container(
                height: 30.0,
                alignment: Alignment.center,
                width: 80.0,
                decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(15.0),
                  border: Border.all(width: 1.0, color: Colors.blue),
                ),
                child: Text(
                  '殘忍拒絕',
                  style: TextStyle(fontSize: 14.0, color: Colors.blue),
                ),
              ),
              onPressed: () {
                if (widget.entity.isForceUpdate) {
                  exit(0);
                } else {
                  Navigator.of(context).pop();
                }
              },
            ),
            Padding(padding: EdgeInsets.all(10.0)),
            CupertinoButton(
              padding: EdgeInsets.zero,
              child: Container(
                height: 30.0,
                alignment: Alignment.center,
                width: 80.0,
                decoration: BoxDecoration(
                  color: Colors.blue,
                  borderRadius: BorderRadius.circular(15.0),
                ),
                child: Text(
                  '立即更新',
                  style: TextStyle(fontSize: 14.0, color: Colors.white),
                ),
              ),
              onPressed: () async {
                print(Platform.isAndroid.toString());
                if (Platform.isAndroid) {
                  download();
                } else if (Platform.isIOS) {
                  final url = "https://itunes.apple.com/cn/app/id1380512641";
                  if (await canLaunch(url)) {
                    await launch(url, forceSafariVC: false);
                  } else {
                    throw 'Could not launch $url';
                  }
                }
              },
            )
          ],
        );
      case DownloadStatus.busy:
        return Padding(
          padding: EdgeInsets.all(5.0),
          child: Column(
            children: <Widget>[
              Text('已下載' + _currentProgressPresent),
              LinearProgressIndicator(
                backgroundColor: Colors.blue[200],
                valueColor: AlwaysStoppedAnimation(Colors.blue),
                value: _currentProgress,
              )
            ],
          ),
        );
      case DownloadStatus.finish:
        return CupertinoButton(
          padding: EdgeInsets.zero,
          child: Container(
            alignment: Alignment.center,
            margin: EdgeInsets.all(5.0),
            height: 30.0,
            child: Text(
              '已下載，點擊安裝',
              style: TextStyle(fontSize: 14.0, color: Colors.white),
            ),
            decoration: BoxDecoration(
              color: Colors.blue,
              borderRadius: BorderRadius.circular(15.0),
            ),
          ),
          onPressed: () {
            installApk();
          },
        );
      case DownloadStatus.error:
        return CupertinoButton(
          padding: EdgeInsets.zero,
          child: Container(
            alignment: Alignment.center,
            margin: EdgeInsets.all(5.0),
            height: 30.0,
            child: Text(
              '下載出錯，請重試',
              style: TextStyle(fontSize: 14.0, color: Colors.white),
            ),
            decoration: BoxDecoration(
              color: Colors.blue,
              borderRadius: BorderRadius.circular(15.0),
            ),
          ),
          onPressed: () {
            download();
          },
        );
    }
  }

  download() async {
    var status = await Permission.storage.request();
    if (status.isGranted) {
      setState(() {
        _downloadStatus = DownloadStatus.busy;
      });
      Directory dir = await getExternalStorageDirectory();
      if (!await dir.exists()) {
        await dir.create();
      }
      _file = new File(dir.path + "/data/update.apk");
      if (await _file.exists()) {
        await _file.delete();
      }
      print(_file.path);
      try {
        Response res = await dio.download(widget.entity.updateUrl, _file.path,
            onReceiveProgress: (count, total) {
          if (total != -1) {
            setState(() {
              _currentProgress = count / total;
              _currentProgressPresent =
                  ((count / total * 100).toStringAsFixed(0) + "%");
            });
          }
        });
        setState(() {
          _downloadStatus = res.statusCode == 200
              ? DownloadStatus.finish
              : DownloadStatus.error;
        });
      } catch (e) {
        print(e);
        setState(() {
          _downloadStatus = DownloadStatus.error;
        });
      }
    }
  }

  Future<Null> installApk() async {
    if (!await _file.exists()) {
      setState(() {
        _downloadStatus = DownloadStatus.easy;
      });
    }
    PackageInfo packageInfo = await PackageInfo.fromPlatform();
    InstallPlugin.installApk(_file.path, packageInfo.packageName)
        .then((result) {
      print('install apk $result');
    }).catchError((error) {
      print('install apk error: $error');
    });
  }
}
